﻿using Autofac;
using CrawlerApp.Services.Interfaces.Job;
using CrawlerApp.Services.Job;
using Quartz;
using Quartz.Spi;
using Serilog;
using System.Threading.Tasks;

// 单纯的爬虫用不上PuppeteerSharp，爬取速度太慢了

namespace CrawlerApp.Services
{
    public class JobService : IJobService
    {
        private readonly IScheduler scheduler;
        private readonly ILogger logger;

        public bool IsStarted => scheduler.IsStarted;
        public bool IsShutdown => scheduler.IsShutdown;

        public JobService(ILogger logger, ILifetimeScope lifetimeScope)
        {
            this.logger = logger.ForContext<JobService>();
            scheduler = lifetimeScope.Resolve<ISchedulerFactory>().GetScheduler().Result;
            scheduler.JobFactory = lifetimeScope.Resolve<IJobFactory>();
        }

        public async Task Start()
        {
            if (!scheduler.IsStarted)
            {
                logger.Information($"开始任务调度");
                await scheduler.Start();
                await CreateAllJob();
            }
        }

        public async Task Shutdown()
        {
            if (!scheduler.IsShutdown)
            {
                await scheduler.Shutdown();
                logger.Information("停止任务调度");
            }
        }

        private async Task CreateAllJob()
        {
            //await CreateJob<CategoryJob>();
            //await CreateJob<TagJob>();
            await CreateJob<BookJob>();
        }

        private async Task CreateJob<T>() where T: IJob
        {
            IJobDetail job = JobBuilder.Create<T>()
                .WithIdentity(typeof(T).Name)
                .Build();

            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity(typeof(T).Name)
                .StartNow()
                .Build();

            await scheduler.ScheduleJob(job, trigger);
        }
    }
}
